import React, { useState, useEffect } from 'react';
import {
  Layout,
  Menu,
  Button,
  Form,
  Select,
  Space,
  Row,
  Col,
  Alert,
  Badge,
  Avatar,
  Steps,
  Tabs,
  Modal,
  message,
  notification,
  Drawer
} from 'antd';
import {
  HomeOutlined,
  StarOutlined,
  BugOutlined,
  CalculatorOutlined,
  HistoryOutlined,
  FileTextOutlined,
  UserOutlined,
  MenuOutlined,
  ThunderboltOutlined
} from '@ant-design/icons';
import Calculator from './Calculator';
import LotteryHistory from './LotteryHistory';
import LotteryNumberPicker from './LotteryNumberPicker';
import LotteryPickingRecords from './LotteryPickingRecords';
import ErrorBoundary from './ErrorBoundary';
import ErrorMonitorPanel from './ErrorMonitorPanel';
import ConfigPage from './ConfigPage';
import errorMonitor from './errorMonitor';
import notchDetector from './notchDetector';
import { useAndroidAdapter } from './AndroidAdapter';
import { DatabaseService } from './database';
import LotteryApiService, { initializeTauriDetection } from './lotteryApi';
import './App.css';
import './AndroidAdapter.css';

const { Header, Content, Footer, Sider } = Layout;
const { Option } = Select;
const { Step } = Steps;

function App() {
  const [collapsed, setCollapsed] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [currentPage, setCurrentPage] = useState('2'); // 默认显示计算器页面
  const [form] = Form.useForm();
  
  // 响应式状态
  const [isMobile, setIsMobile] = useState(false);
  const [isTablet, setIsTablet] = useState(false);
  const [mobileDrawerVisible, setMobileDrawerVisible] = useState(false);
  const [screenSize, setScreenSize] = useState({
    width: window.innerWidth,
    height: window.innerHeight
  });

  // 刘海屏检测状态
  const [, setNotchInfo] = useState({
    isNotchDevice: false,
    safeAreaInsets: { top: 0, right: 0, bottom: 0, left: 0 },
    deviceInfo: {},
    recommendations: []
  });

  // 安卓适配状态
  const androidInfo = useAndroidAdapter();

  // 历史数据状态
  const [historyData, setHistoryData] = useState([]);

  // 初始化错误监控
  useEffect(() => {
    errorMonitor.init();
    
    // 设置错误回调，可以在这里添加自定义处理逻辑
    errorMonitor.setErrorCallback((error) => {
      console.log('错误监控捕获到错误:', error);
      // 这里可以添加发送错误到服务器的逻辑
    });

    return () => {
      // 组件卸载时清理
      errorMonitor.destroy();
    };
  }, []);

  // 应用启动时进行环境检测
  useEffect(() => {
    // 初始化 Tauri 环境检测
    const initializeApp = async () => {
      try {
        // 先初始化 Tauri 环境检测
        await initializeTauriDetection();
        
        // 获取并输出环境信息
        const envInfo = await LotteryApiService.getEnvironmentInfo();
        console.log('=== 应用启动环境检测 ===');
        console.log('环境信息:', JSON.stringify(envInfo, null, 2));
        
        // 如果是Android环境，额外输出调试信息
        if (envInfo.isAndroid) {
          console.log('=== Android环境详细信息 ===');
          console.log('User Agent:', navigator.userAgent);
          console.log('Location:', {
            protocol: window.location.protocol,
            host: window.location.host,
            hostname: window.location.hostname,
            port: window.location.port,
            pathname: window.location.pathname
          });
          console.log('Tauri检测:', {
            '__TAURI__存在': !!window.__TAURI__,
            'protocol是tauri': window.location.protocol === 'tauri:',
            'host是tauri.localhost': window.location.host === 'tauri.localhost',
            'userAgent包含Tauri': navigator.userAgent.includes('Tauri')
          });
        }
      } catch (error) {
        console.error('应用初始化失败:', error);
      }
    };
    
    initializeApp();
  }, []);

  // 数据迁移 - 将localStorage中的选号记录迁移到数据库
  useEffect(() => {
    const migrateData = async () => {
      try {
        const migrated = await DatabaseService.migrateLocalStorageData();
        if (migrated > 0) {
          message.success(`成功迁移 ${migrated} 条历史选号记录到数据库`);
        }
      } catch (error) {
        console.error('数据迁移失败:', error);
        message.error('历史数据迁移失败，但不影响正常使用');
      }
    };

    migrateData();
  }, []);

  // 加载历史开奖数据
  useEffect(() => {
    const loadHistoryData = async () => {
      try {
        const data = await DatabaseService.getAllLotteryHistory();
        setHistoryData(data);
      } catch (error) {
        console.error('加载历史数据失败:', error);
        message.error('加载历史开奖数据失败');
      }
    };

    loadHistoryData();
  }, []);

  // 设备检测
  useEffect(() => {
    const checkDevice = () => {
      const width = window.innerWidth;
      const height = window.innerHeight;
      
      setScreenSize({ width, height });
      setIsMobile(width <= 768);
      setIsTablet(width > 768 && width <= 1024);
      
      // 移动端自动收起侧边栏
      if (width <= 768) {
        setCollapsed(true);
      }

      // 刘海屏检测
      const detectionResult = notchDetector.getDetectionResult();
      setNotchInfo(detectionResult);
      
      // 如果检测到刘海屏，显示通知
      if (detectionResult.isNotchDevice && !sessionStorage.getItem('notch-detected')) {
        notification.info({
          message: '刘海屏设备检测',
          description: `检测到刘海屏设备，已自动适配安全区域。顶部安全区域: ${detectionResult.safeAreaInsets.top}px`,
          duration: 4,
          placement: 'topRight'
        });
        sessionStorage.setItem('notch-detected', 'true');
      }

      // 如果检测到安卓设备，显示适配通知
      if (androidInfo.isAndroid && !sessionStorage.getItem('android-adapted')) {
        notification.success({
          message: '安卓设备适配',
          description: `检测到安卓设备${androidInfo.androidVersion ? ` (Android ${androidInfo.androidVersion})` : ''}，已自动应用界面适配优化。`,
          duration: 3,
          placement: 'topRight'
        });
        sessionStorage.setItem('android-adapted', 'true');
      }
    };

    checkDevice();
    window.addEventListener('resize', checkDevice);
    window.addEventListener('orientationchange', () => {
      setTimeout(checkDevice, 100); // 延迟检测，等待方向改变完成
    });

    // 监听刘海屏方向变化
    const unsubscribe = notchDetector.onOrientationChange((result) => {
      setNotchInfo(result);
    });

    return () => {
      window.removeEventListener('resize', checkDevice);
      window.removeEventListener('orientationchange', checkDevice);
      unsubscribe();
    };
  }, [androidInfo.androidVersion, androidInfo.isAndroid]);

  // 菜单项
  const menuItems = [
    {
      key: '1',
      icon: <HomeOutlined />,
      label: '配置',
    },
    {
      key: '2',
      icon: <CalculatorOutlined />,
      label: isMobile ? '计算器' : '矩阵计算器',
    },
    {
      key: '3',
      icon: <HistoryOutlined />,
      label: '选号记录',
    },
    {
      key: '4',
      icon: <FileTextOutlined />,
      label: '历史记录',
    },
    {
      key: '5',
      icon: <ThunderboltOutlined />,
      label: '智能选号',
    },
    {
      key: '6',
      icon: <BugOutlined />,
      label: '错误监控',
    },
  ];

  // 菜单点击处理
  const handleMenuClick = ({ key }) => {
    setCurrentPage(key);
    if (isMobile) {
      setMobileDrawerVisible(false);
    }
  };

  // 移动端菜单切换
  const toggleMobileMenu = () => {
    setMobileDrawerVisible(!mobileDrawerVisible);
  };

  return (
    <ErrorBoundary>
      <Layout className={`responsive-layout safe-area-container ${isMobile ? 'mobile-layout' : ''} ${androidInfo.isAndroid ? 'android-layout-container' : ''}`} style={{ minHeight: '100vh' }}>
      {/* 桌面端侧边栏 */}
      {!isMobile && (
        <Sider 
          collapsible 
          collapsed={collapsed} 
          onCollapse={setCollapsed}
          width={isTablet ? 180 : 200}
          className={androidInfo.isAndroid ? 'android-sider' : ''}
        >
          <div style={{ height: 32, margin: 16, background: 'rgba(255, 255, 255, 0.3)' }} />
          <Menu 
            theme="dark" 
            selectedKeys={[currentPage]} 
            mode="inline" 
            items={menuItems} 
            onClick={handleMenuClick}
          />
        </Sider>
      )}

      {/* 移动端抽屉菜单 */}
      {isMobile && (
        <Drawer
          title="菜单"
          placement="left"
          onClose={() => setMobileDrawerVisible(false)}
          open={mobileDrawerVisible}
          styles={{ body: { padding: 0 } }}
          width={250}
        >
          <Menu 
            selectedKeys={[currentPage]} 
            mode="inline" 
            items={menuItems} 
            onClick={handleMenuClick}
            style={{ border: 'none' }}
          />
        </Drawer>
      )}
      
      <Layout className={`site-layout ${isMobile ? 'mobile-content' : ''}`}>
        <Header 
          className={`${isMobile ? 'mobile-header mobile-header-safe safe-area-header' : 'safe-area-header'} ${androidInfo.isAndroid ? 'android-header' : ''}`}
          style={{ 
            padding: '0 24px', 
            background: '#fff',
            height: isMobile ? '56px' : '64px',
            lineHeight: isMobile ? '56px' : '64px'
          }}
        >
          <Row justify="space-between" align="middle" style={{ height: '100%' }}>
            {/* 左侧：移动端菜单按钮 */}
            <Col>
              {isMobile && (
                <Button
                  icon={<MenuOutlined />}
                  onClick={toggleMobileMenu}
                  type="text"
                  size="large"
                  style={{ 
                    fontSize: '18px',
                    height: '40px',
                    width: '40px'
                  }}
                />
              )}
            </Col>
            
            {/* 中间：标题 */}
            <Col flex="auto" style={{ textAlign: 'center' }}>
              <h2 style={{ 
                margin: 0,
                fontSize: isMobile ? '18px' : '20px',
                fontWeight: 'bold'
              }}>
                <CalculatorOutlined style={{ marginRight: '8px' }} />
                计算器
              </h2>
            </Col>
            
            {/* 右侧：用户信息和通知 */}
            <Col>
              <Space size={isMobile ? 'small' : 'middle'}>
                <Badge count={5}>
                  <Avatar 
                    shape="square" 
                    icon={<UserOutlined />} 
                    size={isMobile ? 'small' : 'default'}
                  />
                </Badge>

              </Space>
            </Col>
          </Row>
        </Header>
        
        <Content 
          className={`${isMobile ? 'mobile-content-inner safe-area-content' : 'safe-area-content'} ${androidInfo.isAndroid ? 'android-content' : ''}`}
          style={{ 
            margin: isMobile ? '8px' : '16px'
          }}
        >
          <div style={{ 
            padding: isMobile ? 12 : 24, 
            minHeight: 360, 
            background: '#fff' 
          }}>
            
            {/* 配置页面 */}
            {currentPage === '1' && (
              <ConfigPage isMobile={isMobile} />
            )}
            
            {/* 计算器页面 */}
            {currentPage === '2' && (
              <Calculator isMobile={isMobile} />
            )}
            
            {/* 选号记录页面 */}
            {currentPage === '3' && (
              <LotteryPickingRecords isMobile={isMobile} historyData={historyData} />
            )}
            
            {/* 历史记录页面 */}
            {currentPage === '4' && (
              <LotteryHistory isMobile={isMobile} />
            )}
            
            {/* 智能选号页面 */}
            {currentPage === '5' && (
              <LotteryNumberPicker isMobile={isMobile} />
            )}
            
            {/* 错误监控页面 */}
            {currentPage === '6' && (
              <ErrorMonitorPanel isMobile={isMobile} />
            )}
            


          </div>
        </Content>
        
        <Footer 
          className={`safe-area-footer ${androidInfo.isAndroid ? 'android-footer' : ''}`}
          style={{ 
            textAlign: 'center',
            padding: isMobile ? '16px 12px' : '24px 50px',
            fontSize: isMobile ? '12px' : '14px'
          }}
        >
          Ant Design ©2024 Created by Ant UED
        </Footer>
      </Layout>

      {/* 模态框 */}
      <Modal
        title="模态框示例"
        open={modalVisible}
        onOk={() => {
          message.success('确认操作成功！');
          setModalVisible(false);
        }}
        onCancel={() => setModalVisible(false)}
        className={`${isMobile ? 'mobile-modal' : ''} ${androidInfo.isAndroid ? 'android-modal' : ''}`}
        width={isMobile ? '90%' : 520}
        centered={isMobile}
      >
        <p>这是一个模态框的内容示例。</p>
        <p>您可以在这里放置任何内容。</p>
        {isMobile && (
          <p style={{ fontSize: '12px', color: '#999' }}>
            当前设备: 移动端 ({screenSize.width}x{screenSize.height})
          </p>
        )}
      </Modal>
      </Layout>
    </ErrorBoundary>
  );
}

export default App;
